package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.iot.base.service.req.DataBag;
import com.iot.base.service.req.DataParam;
import com.iot.sdk.yugong.resp.YuGongRespData;
import com.iot.sdk.yugong.resp.YuGongRespDataList;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanSettingParam;
import com.yx.cloud.Interface.OnItemClickListener;
import com.yx.cloud.R;
import com.yx.cloud.adapter.VoiceListAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.VoiceInfoBean;
import com.yx.cloud.databinding.VoicevolumesettingActivityBinding;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.Robot;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 语音及音量设置界面
 */
public class VoiceVolumeSettingActivity extends BaseActivity implements SeekBar.OnSeekBarChangeListener, View.OnClickListener {

    private final static String TAG = "VoiceVolumeSettingActivity";
    VoiceListAdapter adapter;
    private List<VoiceInfoBean> mVoiceList;
    private VoiceInfoBean voiceInfoBean;
    private VoicevolumesettingActivityBinding binding;
    private String file_name, describe_file;
    private CleanSettings settings;
    private int selectPosition = 0;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onCreate() {
        binding = VoicevolumesettingActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @SuppressLint("LongLogTag")
    @TargetApi(Build.VERSION_CODES.M)
    private void initData() {
        Robot robot = AppContext.get().getCurrentDevice();
        settings = robot.getCleanSettings();

        //根据机器型号进行 查看地图UI 显示
        binding.volumeSettingSeekBar.setMax(100);

        int volume = settings.getVolume();
        mVoiceList = new ArrayList<>();
        binding.volumeSettingSeekBar.setProgress(volume);
        binding.volumeSettingSeekBar.setOnSeekBarChangeListener(this);

        binding.rvVoideView.setLayoutManager(new LinearLayoutManager(this));
//        binding.rvVoideView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new VoiceListAdapter(this, mVoiceList);
        binding.rvVoideView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                selectPosition = position;
                TextView voice_use = view.findViewById(R.id.tv_voice_use);
                String s = voice_use.getText().toString();
                if (getString(R.string.MO_Use_Btn).equals(s)) {
                    for (int i = 0; i < mVoiceList.size(); i++) {
                        VoiceInfoBean bean = mVoiceList.get(position);
                        if (position == i) {
                            file_name = bean.getShowName(); // Chinese English
                            describe_file = bean.getDescribe_file();//1000
                            bean.setStauts(2);//点击手动设置为加载中
                            bean.setSelected(true);
                        }
                    }
                    adapter.updateVoiceList(mVoiceList);

                    DataParam param = new DataParam();
                    param.setData_type("voice_package");
                    param.setFile_name(file_name);
                    AppContext.getProductService().getData(param);
                }
            }
        });
        binding.ivVoiceReturn.setOnClickListener(this);

        DataParam param = new DataParam();
        param.setData_type("voice_package");
        AppContext.getProductService().getDataList(param);

    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_voiceReturn) {
            Intent_utils.backIntent(this);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("LongLogTag")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_VOICE_LIST:
                //获取语音列表
                YuGongRespDataList yuGongRespDataList = (YuGongRespDataList) event.getContent();
                List<YuGongRespDataList.ResourceListBean> resource_list = yuGongRespDataList.getResource_list();
                LogUtils.i(settings.getCurrentLanguage() + " : 数据列表 bbb :" + new Gson().toJson(resource_list));
                for (int i = 0; i < resource_list.size(); i++) {
                    voiceInfoBean = new VoiceInfoBean();
                    voiceInfoBean.setShowName(resource_list.get(i).getFile_name());
                    voiceInfoBean.setDescribe_file(resource_list.get(i).getDescribe_file());
                    if (settings.getCurrentLanguage().equals(resource_list.get(i).getFile_name())) {
                        voiceInfoBean.setStauts(3);
                        voiceInfoBean.setSelected(true);
                    }
                    mVoiceList.add(voiceInfoBean);
                }
                updateVoiceList(mVoiceList);
                break;
            case Event.MESSAGE_TYPE_GET_DATA:
                //获取语言url
                YuGongRespData content = (YuGongRespData) event.getContent();
                List<YuGongRespData.FileListBean> file_list = content.getFile_list();
                String s3Url = file_list.get(0).getData_s3_url();

                DataBag dataBag = new DataBag();
                dataBag.setType(file_name);
                dataBag.setUrl(s3Url);
                dataBag.setVersion(describe_file);
                AppContext.getProductService().sendVoiceBagUrlToDevice(dataBag);
                break;
            case Event.MESSAGE_TYPE_DATA_FUNC:
                //设置结果 -1 下载失败 0下载成功 1 下载中
                String dataFunc = (String) event.getContent();
                LogUtils.i(" : 数据 下载成功 :" + dataFunc);
                try {
                    JSONObject jsonObject = new JSONObject(dataFunc);
                    int progress = jsonObject.getInt("progress");
                    if (progress == 100) {
                        int status = jsonObject.getInt("status");
                        if (0 == status) {
                            for (int i = 0; i < mVoiceList.size(); i++) {
                                if (i == selectPosition) {
                                    mVoiceList.get(i).setStauts(3);
                                    mVoiceList.get(i).setSelected(true);
                                } else {
                                    mVoiceList.get(i).setStauts(2);
                                    mVoiceList.get(i).setSelected(false);
                                }
                            }
                            updateVoiceList(mVoiceList);
                        } else if (-1 == status) {
                            for (int i = 0; i < mVoiceList.size(); i++) {
                                if (i == selectPosition) {
                                    mVoiceList.get(i).setStauts(2);
                                    mVoiceList.get(i).setSelected(true);
                                }
                            }
                            updateVoiceList(mVoiceList);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case Event.MESSAGE_TYPE_VOICE_STATUS_RESULT:
                updateVoiceList(mVoiceList);
                break;
        }
    }

    public void updateVoiceList(List<VoiceInfoBean> voiceList) {
//        CleanSettings cleanSettings = AppContext.get().getCurrentDevice().getCleanSettings();
//        int voiceId = Integer.parseInt(cleanSettings.getVoiceType());
//        int voiceBagStatus = cleanSettings.getVoiceBagStatus();
//
//        LogUtils.i("voiceId " + voiceId);
//        LogUtils.i("voiceBagStatus " + voiceBagStatus);
//        if (voiceList != null && voiceList.size() > 0) {
//            for (VoiceInfoBean voiceInfoBean : voiceList) {
//                LogUtils.i("voiceInfoBean id " + voiceInfoBean);
//                if (voiceInfoBean.getId() == voiceId) {
//                    voiceInfoBean.setSelected(true);
//                    voiceInfoBean.setStauts(voiceBagStatus);
//                } else {
//                    voiceInfoBean.setSelected(false);
//                }
//            }
//        }
        adapter.updateVoiceList(voiceList);
    }

    //设置音量
    @SuppressLint("LongLogTag")
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.i(TAG, "--onProgressChanged -- " + progress);
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        Log.i(TAG, "--onStartTrackingTouch -- ");
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //设置音量
        int progress = seekBar.getProgress();
        AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().volume(progress).build());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
